
var oldSelected= null;
var editor = null;
var editor3= null;


setTimeout(function () {
    if(vfs) {
         vfs.mount("data.rsl" , function (e) {
             console.log(e);
             if(e=="data.rsl") {
                 Runner();
             }
         });
    }
    
},500);

    
function Runner () {
    initMacros ();
    initCodeMir();
    initEditor ();
    initCaseList();
    initCtrls ();
    defaultDisplay();
}

function defaultDisplay() {
    setTimeout(function () {
            var index   = 0 >> 0;
            oldSelected = $(".listview-outlook")[index];
            var name = $(oldSelected).attr("itemname");
            var code = vfs.getFileContent(name)
            $(oldSelected).addClass("active");
            
            if(document.getElementById("codec") != null) {
            	code =  document.getElementById("codec") .innerText;
            	if(code) {
	                editor.setValue(code);
	            }
            }
          
    }, 0)
}

var cls = {}
cls.download_create= function () {
        var container = document.createElement('ol');
        container.style.backgroundColor="#FFFFFF";
        container.style.zIndex= 9999;
        container.id = "dl_containre"
        container.style['float']="right";
        document.body.appendChild(container);
    }
    
    cls.createCounter = 0;
    cls.download_test = function (arrbuffer, n,tl) {
        if(cls.createCounter == 0) {
            cls.download_create();
        }
        var container = document.getElementById("dl_containre");
        var li = document.createElement('li')
        var blob = new Blob([arrbuffer]);
        var aLink = document.createElement('a');
        aLink.innerText= n;
        aLink.style.background="#FFFFFF"
        aLink.style.color="#FF0000";
        aLink.style.textAlign="center";
        
        var url  =  URL.createObjectURL(blob);
        var evt = document.createEvent("HTMLEvents");
        aLink.download = n + "";
        aLink.href = tl;
        li.appendChild(aLink);
        container.appendChild(li);
}
    
    
function initCtrls () {
        
     $("#run").click(function () {
           console.log = function (v) {
//              var logger =  document.getElementById("logger");
//              if(logger &&  v.indexOf("%") == -1 ) {
//                  var line = document.createElement("li");
//                  line.style.color="#FFFFFF"
//                  line.innerText = v;
//                  logger.appendChild(line)
//              } 
            }
//                     
//          var logger =  document.getElementById("logger");
//          logger.innerHTML = "";
//          var codes = apolloxLua.parse(editor.getValue());
//          if(codes) {
//              if(codes.indexOf("ngx") != -1) {
//                  console.log("context is run in nginx. not web mode");   
//                  codes += "--web 模式下链接入标准库代码。nginx模式自动引用库。"
//                  editor3.setValue(codes);
//                  metroDialog.open('#dialog3');
//                  return;
//              }
//          }
            
            //showMetroCharm($("#console"));
            //if(L) {
            //    L.execute(codes);
            //}
            
            var need   = editor.getValue();
                 var codes = apolloxLua.parse(need);
                if(need) {
                  
                   var ast = luaparse.parse(codes, { 'scope': true });
                   
                   need  = luamin.minify(ast);
                   codes = "--[dssa/main]\n" + need;
                }
                
                var pngdrive = new PNGDrive();
                pngdrive.addTextFile(codes, "file" + pngdrive.getFileCount() + ".txt", "text/plain");
                pngdrive.encode(function() {
                        var img =  this.createImage();
                        var ctx =  img.getContext("2d");
                        if(ctx) {
                             var canvas = ctx.canvas;
                             var bytes  = ctx.getImageData(0,0,canvas.width, canvas.height).data;
                             window.frames[0].postMessage(codes, "*");
                        }
                });
            
        })
        
        
        $("#raw").click(function (e) {
                var codes = apolloxLua.parse(editor.getValue());
                editor3.setValue(codes);
                metroDialog.open('#dialog3');
        })
        
        $("#savecode").click(function (e) {
        	alert("mail to : agent.zy@aliyun.com");
        	return;
                var need   = editor.getValue();
                 var codes = apolloxLua.parse(need);
                if(need) {
                  
                   var ast = luaparse.parse(codes, { 'scope': true });
                   
                   need  = luamin.minify(ast);
                   codes = "--[dssa/main]\n" + need;
                   
                   //L.execute(codes);
                   console.log(codes);
                }
                
                var pngdrive = new PNGDrive();
                pngdrive.addTextFile(codes, "file" + pngdrive.getFileCount() + ".txt", "text/plain");
                pngdrive.encode(function() {
                        var img =  this.createImage();
                        var ctx =  img.getContext("2d");
                        if(ctx) {
                             var canvas = ctx.canvas;
                             var bytes  = ctx.getImageData(0,0,canvas.width, canvas.height).data;
                             //console.error("dump wasm codes=>", bytes);
                             //cls.download_test(0, "base.wasm", img.toDataURL());
                        }
                });
         
        });
        
      
}

function initCodeMir () {
    editor3 = ace.edit("editor3");
    editor3.session.setMode("ace/mode/lua");
    editor3.setFontSize(16);
    editor3.setOptions({
         enableBasicAutocompletion: false,
         enableLiveAutocompletion: false
    });
    editor3.$blockScrolling = Infinity;
    editor3.commands.addCommand({
    name: 'myCommand',
    bindKey: {win: 'Ctrl-S',  mac: 'Command-S'},
    exec: function(editor) {
        }
    });
    editor3.setTheme("ace/theme/xcode");
}

function initMacros() {
    window.macros = {
		"CODE_TYPE":"A",
		"USE_AOP":1
	}
}

function initEditor() {
    editor = ace.edit("editor");
    editor.session.setMode("ace/mode/javascript");
    editor.setFontSize(16);
    editor.setOptions({
         enableBasicAutocompletion: false,
         enableLiveAutocompletion: false
    });
    editor.$blockScrolling = Infinity;
    editor.commands.addCommand({
    name: 'myCommand',
    bindKey: {win: 'Ctrl-S',  mac: 'Command-S'},
    exec: function(editor) {
        }
    });
    editor.setTheme("ace/theme/xcode");
}

function initCaseList () {
    var listCellHtmlRaw  = [];
    var data = vfs.listFileNames();
    var index = 0;
    for(var i=0;i<data.length; i++) {
        var k = data[i];
        if(k.indexOf("case") > 0)  {
             listCellHtmlRaw.push((function (ctx) {
                return  Tml(ITEM_RENDER_CELL, ctx)
                })({itemIndex:i,itemName:k}));
        }
    }
    $("#caseContainer").html(listCellHtmlRaw.join(""));
}

function selectEventHandle(e) {
    if(oldSelected) {
        $(oldSelected).removeClass("active");
    }
    var name = $(e.currentTarget).attr("itemname");
    oldSelected = $(e.currentTarget);
    var code = vfs.getFileContent(name)
    if(code) {
        editor.setValue(code);
    }
    e.stopPropagation();
}
